package cn.cxy.grideviewdemo

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import java.util.*

class FlowerAdapter(private val context: Context, dataList: List<Flower>) : BaseAdapter() {
    private var mDataList = ArrayList<Flower>()
    private val mInflater: LayoutInflater

    init {
        mDataList.addAll(dataList)
        mInflater =
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
    }

    override fun getCount(): Int {
        return mDataList.size
    }

    override fun getItem(position: Int): Any {
        return mDataList[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(
        position: Int,
        _convertView: View?,
        parent: ViewGroup
    ): View {
        var convertView: View
        val holder: ViewHolder
        if (_convertView == null) {
            holder = ViewHolder()
            convertView = mInflater.inflate(R.layout.adapter_flower, null)
            holder.nameTv = convertView.findViewById(R.id.textView)
            holder.imageView = convertView.findViewById(R.id.photoView)
            convertView.tag = holder
        } else {
            convertView = _convertView
            holder = convertView.tag as ViewHolder
        }

        if (mDataList[position] != null) {
            holder.nameTv?.text = mDataList[position].flowerName
            holder.imageView?.let {
                Glide.with(context).load(mDataList[position].imagePath).into(it)
            }

        }
        return convertView
    }

    private class ViewHolder {
        var nameTv: TextView? = null
        var imageView: ImageView? = null
    }


}